package work20241226;

/**
 * @author zdl
 * @date 2024/12/26
 */
class PrintNum{
    private Integer num;
    private boolean flag;

    public PrintNum() {
    }

    public PrintNum(Integer num, boolean flag) {
        this.num = num;
        this.flag = flag;
    }

    /**
     * 获取
     * @return num
     */
    public Integer getNum() {
        return num;
    }

    /**
     * 设置
     * @param num
     */
    public void setNum(Integer num) {
        this.num = num;
    }

    /**
     * 获取
     * @return flag
     */
    public boolean isFlag() {
        return flag;
    }

    /**
     * 设置
     * @param flag
     */
    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public String toString() {
        return "PrintNum{num = " + num + ", flag = " + flag + "}";
    }
}
class ThreadPrint1 implements Runnable{
    private PrintNum printNum;
    public ThreadPrint1(PrintNum printNum){
        this.printNum = printNum;
    }

    @Override
    public void run() {
        while (true){
            synchronized (printNum){
                //打印奇数
                if (printNum.isFlag()){
                    System.out.println(Thread.currentThread().getName()+"线程打印:"+printNum.getNum());
                    printNum.notify();
                    printNum.setFlag(false);
                }else {
                    try {
                        printNum.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
class ThreadPrint2 implements Runnable{
    private PrintNum printNum;
    public ThreadPrint2(PrintNum printNum){
        this.printNum = printNum;
    }

    @Override
    public void run() {
        while (true){
            synchronized (printNum){
                //打印偶数
                if (printNum.isFlag()){
                    try {
                        printNum.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }else {
                    printNum.setNum(99999999);
                    System.out.println(Thread.currentThread().getName()+"线程打印:"+printNum.getNum());
                    printNum.notify();
                    printNum.setFlag(true);
                }
            }
        }
    }
}
public class Demo11 {
    public static void main(String[] args) {
        //11. 编写一个程序，使用同步代码块确保两个线程能够交替打印数字。
        PrintNum printNum = new PrintNum(10,false);
        ThreadPrint1 print1 = new ThreadPrint1(printNum);
        ThreadPrint2 print2 = new ThreadPrint2(printNum);
        new Thread(print1,"线程1：").start();
        new Thread(print2,"线程2：").start();

    }
}
